package org.langqiao.io.encrypt;

/**
 * 加密算法
 * @author YMY
 */

import java.util.Scanner;
public class EncryptTest {
	
	public static void main(String[] args) {
		char alph[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};//字母表数组
		//s为密钥,s1为原文
		String s,s1;
		int k = 0,t = 0;
		//定义一个密文字符数组
		char[] miwen = new char[50];
		Scanner sc = new Scanner(System.in);
		do{
			System.out.println("请输入密钥：");
			//输入密钥
		    s=sc.nextLine();
		}while(s.length()>25);
		//char[] key=new char[25];
		char[] key=s.toCharArray();
		do {
			System.out.println("请输入原文：");
			s1=sc.nextLine();
		}while(s1.length()>50);
		
		char[] yuanwen = s1.toCharArray();//将原文字符窜转换为字符数组
		char a[][] = new char[6][6];
		//一个5行5列的矩阵，将密钥和除密钥以外的字母填充到这个5行5列的方阵中
		for(int i = 0;i < 5;i++) {
			for(int j=0;j<5;j++) {
				if(key[k]!='\0'){
					a[i][j]=key[k];
					k++;
				} else{
					while(find(key,key.length,alph[t]))
						t++;
					a[i][j]=alph[t];
					t++;
				}
			}
		}
//		int x,y;
		char t1,t2;
		int i1=-1,j1=-1,i2=-1,j2=-1;
		//自加2使每次一对对的查找
		for(int i=0;i<yuanwen.length;i+=2) {
			t1=yuanwen[i];
			t2=yuanwen[i+1];
			if(t1==t2||t2=='\0') {
				miwen[i]=t1;
			    miwen[i+1]=t2;
			} else {
				find_juzhen(a,t1,i1,j1);
				find_juzhen(a,t2,i2,j2);
				if(i1==-1||j1==-1||i2==-1||j2==-2) {
					miwen[i]=t1;
					miwen[i+1]=t2;
				} else if(i1==i2||j1==j2) {
				    miwen[i]=t2;
				    miwen[i+1]=t1;
				} else {
					miwen[i]=a[i1][j2];
					miwen[i+1]=a[i2][j1];
				}
			}
		}
		System.out.println("加密后的密文为：");
		for(int i=0;i<miwen.length;i++) {
		   System.out.print(miwen[i]);
		}
	}
	
	public static boolean find(char[] key,int n,char c) {
		boolean flag = false;
		for(int i = 0;i < n;i++) {
			if(key[i] == c)
				flag = true;
				break;
		}
		return flag;
	}
	
	public static void find_juzhen(char[][] a,char c,int i1,int j1 ) {
		for(int i=0;i<5;i++) {
			for(int j=0;j<5;j++) {
				if(a[i][j]==c) {
				   i1=i;
				   j1=j;
				   break;
				}
			}
		}
	}
}
